﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using WindowsFormsApplication3.Datalayer;
using WindowsFormsApplication3.Properties;
namespace WindowsFormsApplication3
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(OnUnhandledException);
            GlobalApplicationContext ApplicationContext;
            AppDomain.CurrentDomain.SetData("DataDirectory",Application.StartupPath);
            try
            {
                ConnStr = Settings.Default.DBConnectionString;
               ApplicationContext = new GlobalApplicationContext();
               //This call will continue message loop or application
               if(!ApplicationContext.MainForm.IsDisposed )
               Application.Run(ApplicationContext);
            }
            catch (Exception appexp)
            {
                MessageBox.Show(appexp.Message + appexp.StackTrace);
            }
        }
        public static string ConnStr=null;
        private static void OnUnhandledException(object sender, ThreadExceptionEventArgs t)
        {

        }
        class GlobalApplicationContext : ApplicationContext
        {
            public  GlobalApplicationContext()
            {
                MainMenuForm AppForm = new MainMenuForm();
                this.MainForm = AppForm;
                bool showlogin = true;
                while (showlogin)
                {
                    LoginForm login = new LoginForm();
                    DialogResult res = login.ShowDialog();

                    if (res == DialogResult.OK)
                    {
                        if (Datalayer.Login.Authenticate(login.Uname, login.Pwd))
                        {
                            AppForm.Show();
                            showlogin = false;
                        }
                        else
                        {
                            MessageBox.Show("Enter an valid username or password");
                            showlogin = true;
                        }
                    }
                    else
                    {
                        AppForm.Dispose(); AppForm = null;
                        showlogin = false;
                    }
                }
            }
            private void OnApplicationExit(object sender, EventArgs e)
            {

            }
 
        }
    }
}
